package com.example.homework8;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.example.homework8.bean.UserInfo;
import com.example.homework8.database.UserHelper;
import com.example.homework8.utils.BitmapUtil;
import com.example.homework8.utils.FileUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

public class RegisterActivity extends AppCompatActivity {
    UserHelper helper = null;
    private EditText register_user, register_password,phoneed,classnameed;
    private Button register_sure;
    ImageView imageView,imgedit;
    private TimePickerView pvTime;
    TextView birthday;
    String imgurl ="";
    RadioButton manrad ,womanrad;
    @SuppressLint("WrongViewCast")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);

        requestReadExternalPermission();
        requestWriteExternalPermission();
        //创建数据库
        helper = new UserHelper(this, "SAVE_USER1.db", null, 1);
        SQLiteDatabase database = helper.getWritableDatabase();
        register_user = (EditText) findViewById(R.id.edt1);
        register_password = (EditText) findViewById(R.id.edt2);
        birthday = (TextView) findViewById(R.id.birthday);
        register_sure = (Button) findViewById(R.id.btn1);
        manrad= (RadioButton) findViewById(R.id.man_rad);
        womanrad = (RadioButton) findViewById(R.id.woman_rad);
        imageView = (ImageView) findViewById(R.id.imageView);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showImageDialog();
            }
        });

        pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                date = date;
                birthday.setText(new SimpleDateFormat("yyyy年MM月dd日 HH:mm").format(date));
            }
        }).setType(new boolean[]{true, true, true, true, true, false}).build();

        imgedit = (ImageView) findViewById(R.id.imgedit);
        imgedit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pvTime.show();
            }
        });
    }
    public static void copyFile(String oldPath, String newPath, Handler handler) {
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            if (oldfile.exists()) {//文件存在时
                InputStream inStream = new FileInputStream(oldPath);//读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1444];
                int length;
                int value = 0 ;
                while ((byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread;//字节数 文件大小
                    value ++ ;  //计数
                    System.out.println("完成"+bytesum+"  总大小");
                    fs.write(buffer, 0, byteread);
                    Message msg  = new Message(); //创建一个msg对象
                    msg.what =110 ;
                    msg.arg1 = value ; //当前的value
                    handler.sendMessage(msg) ;

                    Thread.sleep(10);//每隔10ms发送一消息，也就是说每隔10ms value就自增一次，将这个value发送给主线程处理
                }
                inStream.close();
            }
        } catch (Exception e) {
            System.out.println("复制单个文件操作出错");
            e.printStackTrace();
        }
    }
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // super.onActivityResult(requestCode, resultCode, data);
        if(requestCode ==1){

            Uri uri = data.getData();
            Bitmap bitmap = null;
            try {
                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
            } catch (IOException e) {
                e.printStackTrace();
            }
            imageView.setImageBitmap(bitmap);
            String name = UUID.randomUUID().toString().substring(24)+".png";
            imgurl =  BitmapUtil.saveImgToDisk(name,bitmap);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
    private void showImageDialog() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        // 以startActivityForResult的方式启动一个activity用来获取返回的结果
        startActivityForResult(intent, 1);
    }


    public static Bitmap drawableToBitmap(Drawable drawable) {
        int w = drawable.getIntrinsicWidth();
        int h = drawable.getIntrinsicHeight();

        Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                : Bitmap.Config.RGB_565;
        Bitmap bitmap = Bitmap.createBitmap(w, h, config);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, w, h);
        drawable.draw(canvas);
        return bitmap;
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public void click(View view){
        // trim()去空格
        String RegisterUser = register_user.getText().toString().trim();
        String RegisterPassword = register_password.getText().toString().trim();
        String phone = birthday.getText().toString();
        String classname = manrad.isChecked() ? "男生":"女生";
         List<UserInfo> userinfo = new ArrayList<UserInfo>();

        SQLiteDatabase database = helper.getWritableDatabase();
        //判断输入的账号密码是否为空，是则提示用户输入正确的
        if (RegisterUser.equals("") || RegisterPassword.equals("") ||  birthday.getText().toString().equals("")  || classname.equals("") || imgurl.equals("")) {
            Toast.makeText(RegisterActivity.this, "请输入设置头像，账号，密码，生日，性别", Toast.LENGTH_SHORT).show();
        } else {
            UserInfo user = new UserInfo();
            user.setName(RegisterUser);
            user.setPassword(RegisterPassword);
            userinfo.add(user);
            ContentValues values = new ContentValues();
            //键值对的形式
            values.put("name", RegisterUser);
            values.put("password", RegisterPassword);
            values.put("phone", birthday.getText().toString());
            values.put("classname", manrad.isChecked() ? "男生":"女生" );

            values.put("imgurl", imgurl);
            Log.d("TAG", "click1: insert imgurl "+imgurl);

            //添加到user表
            database.insert("user",null,values);
            Toast.makeText(RegisterActivity.this, "注册成功! ", Toast.LENGTH_LONG).show();
            Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
            startActivity(intent);
        }
    }
    @SuppressLint("NewApi")
    private void requestReadExternalPermission() {
        if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
                checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
        ) {
            Log.d("TAG", "READ permission IS NOT granted...");
            requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE ,Manifest.permission.CAMERA}, 0);

        } else {
            Log.d("TAG", "READ permission is granted...");
        }
    }

    @SuppressLint("NewApi")
    private void requestWriteExternalPermission() {
        if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            Log.d("TAG", "WRITE permission IS NOT granted...");
            requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);

        } else {
            Log.d("TAG", "WRITE permission is granted...");
        }
    }
}
